// ImageRectTool.js
import { limitPointerInImage } from '../utils/imageUtils';
import { newRectFObject } from '../utils/FabricControls';

class RectTool {
    constructor(canvas) {
        this._canvas = canvas;
        this._rect_coords = null;
        this._rect_tmp = null;
        this._closed = true;
        this._callback = null;
    }

    setImage(image) {
        this._image = image;
    }

    setCallback(callback) {
        this._callback = callback;
    }

    onMouseDown(event) {
        // console.log('RectTool::onMouseDown', event);
        let pointer = {
            x: event.absolutePointer.x,
            y: event.absolutePointer.y
        };
        limitPointerInImage(this._image, pointer);

        if (this._closed) {
            this._rect_coords = { left: pointer.x, top: pointer.y };
            this._rect_tmp = newRectFObject(undefined, { left: pointer.x, top: pointer.y, width: 0.1, height: 0.1 });
            this._canvas.add(this._rect_tmp);
            this._closed = false;
        } else {
            this.finish();
        }
    }

    onMouseMove(event) {
        if (this._closed == false && this._rect_coords) {
            let pointer = {
                x: event.absolutePointer.x,
                y: event.absolutePointer.y
            };
            limitPointerInImage(this._image, pointer);

            let width = Math.abs(pointer.x - this._rect_coords.left);
            let height = Math.abs(pointer.y - this._rect_coords.top);
            let left = this._rect_coords.left < pointer.x ? this._rect_coords.left : pointer.x;
            let top = this._rect_coords.top < pointer.y ? this._rect_coords.top : pointer.y;
            this._rect_tmp.set({
                left: left,
                top: top,
                width: width,
                height: height
            });
        }
    }

    handleKeyDown(event) {
        // console.log('RectTool.js handleKeyDown event = ', event);
        let key = event.key.toLowerCase();
        if (key == 'escape') {
            this.clear();
        }
    }

    // 完成当前编辑
    finish() {
        if (this._rect_tmp) {
            this._canvas.remove(this._rect_tmp);
            this._canvas.renderAll();

            // 调用回调函数，新增一个rect标注结果
            this._callback({
                left: this._rect_tmp.left,
                top: this._rect_tmp.top,
                width: this._rect_tmp.width,
                height: this._rect_tmp.height
            });
        }
        this._rect_coords = null;
        this._rect_tmp = null;
        this._closed = true;
    }

    // 取消当前编辑
    clear() {
        if (this._rect_tmp) {
            this._canvas.remove(this._rect_tmp);
            this._canvas.renderAll();
        }

        this._rect_coords = null;
        this._rect_tmp = null;
        this._closed = true;
    }
}

export default RectTool;
